package com.yumei.trader.gym.ktx

import android.annotation.SuppressLint
import android.app.Dialog
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import com.appsflyer.AppsFlyerLib
import com.appsflyer.share.CrossPromotionHelper
import com.github.lzyzsd.jsbridge.BridgeWebView
import com.google.gson.Gson
import com.yumei.trader.gym.R
import org.json.JSONObject
import java.util.*

fun AppCompatActivity.createDialog(url: String, onDismiss: () -> Unit) {
    val activity = this
    val dialog = Dialog(activity)
    val inflate = activity.layoutInflater.inflate(R.layout.webview_layout, null)
    val webView = inflate.findViewById<BridgeWebView>(R.id.webview)
    dialog.setContentView(inflate)
    dialog.setCancelable(false)
    val window = dialog.window
    if (window != null) {
//        val params = window.attributes
//        params.width = WindowManager.LayoutParams.MATCH_PARENT
//        params.height = WindowManager.LayoutParams.MATCH_PARENT
//        window.attributes = params
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        window.setLayout(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT
        )
        window.setBackgroundDrawableResource(android.R.color.transparent)
    }
    dialog.show()
    dialog.webSetting(webView, onDismiss)
    webView.loadUrl(url)
}

@SuppressLint("SetJavaScriptEnabled")
private fun Dialog.webSetting(webView: BridgeWebView, onDismiss: () -> Unit) {
    val webSettings = webView.settings
    webSettings.javaScriptEnabled = true
    webSettings.domStorageEnabled = true

    webView.registerHandler("ottDiscCutter") { data, function ->
        this.dismiss()
        onDismiss()
    }
    webView.registerHandler("timerShooting") { data, function ->
        val jsonObject = JSONObject(data)
        val afMap = Gson().fromJson<HashMap<String, String>>(
            jsonObject.optString("crescentRay"),
            HashMap::class.java
        )
        CrossPromotionHelper.logAndOpenStore(
            context,
            jsonObject.optString("aceElectricKick"),
            "${afMap["starlight"]}",
            afMap
        )
    }
    webView.registerHandler("stopFlashing") { data, function ->
        function.onCallBack(
            AppsFlyerLib.getInstance().getAppsFlyerUID(context)
        )
    }

}
